<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8"/>
    <title>个人中心</title>
</head>
<script src="http://47.106.66.89:8080/js/vue.min.js"></script>
<script src="js/axios.min.js"></script>
<link
        href="http://47.106.66.89:8080/js/ele-2.15.7/theme-chalk/index.css"
        rel="stylesheet"
/>
<script src="http://47.106.66.89:8080/js/ele-2.15.7/index.js"></script>
<link href="./cdn/all.css" media="screen" rel="stylesheet"/>
<script src="./js/star.js"></script>
<link href="./css/myinfo.css" rel="stylesheet"/>
<body>
<div id="app">
    <star>
        <div class="uheader">
            <div class="个人信息">
            <span class="uimg" @click="openupload">
              <img :src="user.avatarUrl"/>
            </span>
                <div  style="display: none">
                    <input ref="imgs" type="file" @change="getFile" name="file" accept="image/*">
                </div>
                <div class="信息">
                    <h1 class="niceng">{{user.username}}</h1>
                    <p class="ueamil">邮箱号: {{user.email}}</p>
                    <p class="ueamil">手机号: {{user.phone}}</p>
                    <div class="iszaixian">
                        <span class="">●</span>
                        <span class="">在线</span>
                    </div>
                </div>
                <div class="点赞">
                    <img :src="imageSrc" @click="toggleLike"/>
                    <span>{{user.like}}</span>
                </div>
            </div>
            <el-divider></el-divider>
            <div class="生日">
                <div class="nvimg">
              <span>
                <img :src="seximg"/>
              </span>
                    <span>{{age}}</span>
                    <span>{{user.birthday}}</span>
                </div>
                <el-divider></el-divider>
                <div class="标签">
                    <el-tag
                            :color="getRandomColor()"
                            :disable-transitions="false"
                            :key="tag"
                            @close="handleClose(tag)"
                            closable
                            effect="dark"
                            v-for="tag in user.tags"
                    >
                        {{tag}}
                    </el-tag>
                    <el-input
                            @blur="handleInputConfirm"
                            @keyup.enter.native="handleInputConfirm"
                            class="input-new-tag"
                            ref="saveTagInput"
                            size="small"
                            v-if="inputVisible"
                            v-model="inputValue"
                    >
                    </el-input>
                        <el-button
                                @click="showInput"
                                class="button-new-tag"
                                size="small"
                                v-else
                        >+ New Tag
                        </el-button
                        >
                </div>
                <el-divider></el-divider>
                <div class="个性签名">
                    <span>个签:</span>
                    <p>{{user.sign}}</p>
                </div>
                <el-divider></el-divider>
<!--                <div class="mt-4">-->
<!--                    <div class="个人空间"></div>-->
<!--                    <div class="个人照片">-->
<!--                        <span>精选照片</span>-->
<!--                    </div>-->
<!--                    <div class="flex space-x-2 mt-2">-->
<!--                        <img-->
<!--                                v-for="img in user.imgs"-->
<!--                                alt="精选照片 1"-->
<!--                                class="w-12 h-12 rounded"-->
<!--                                height="100"-->
<!--                                src="./asset/4.png"-->
<!--                                style="aspect-ratio: 50 / 50; object-fit: cover"-->
<!--                                width="100"-->
<!--                        />-->
<!--                        <img-->
<!--                                alt="精选照片 1"-->
<!--                                class="w-12 h-12 rounded"-->
<!--                                height="100"-->
<!--                                src="./asset/3.png"-->
<!--                                style="aspect-ratio: 50 / 50; object-fit: cover"-->
<!--                                width="100"-->
<!--                        />-->
<!--                    </div>-->
<!--                </div>-->
            </div>
            <div class="bianji">
                <el-button @click="dialogFormVisible = true" style="margin: 0 20px;">编辑资料</el-button>
                <el-dialog :visible.sync="dialogFormVisible" title="编辑资料">
                    <span @click="openupload" >
                        <el-avatar :src="user.avatarUrl" ></el-avatar>
                    </span>
                    <el-form :model="user">
                        <el-form-item :label-width="formLabelWidth" label="昵称">
                            <el-input autocomplete="off" maxlength="36" v-model="user.username">{{user.username}}</el-input>
                        </el-form-item>
                        <el-form-item :label-width="formLabelWidth" label="个签">
                            <el-input autocomplete="off" maxlength="100" placeholder="编辑个签,展示我的独特态度"
                                      v-model="user.sign">
                            </el-input>
                        </el-form-item>
                        <el-form-item :label-width="formLabelWidth" label="性别">
                            <el-select placeholder="请选择" v-model="user.gender">
                                <el-option
                                        :key="item.value"
                                        :label="item.label"
                                        :value="item.value"
                                        v-for="item in options">
                                </el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item :label-width="formLabelWidth" label="邮箱">
                            <el-input autocomplete="off" maxlength="100" placeholder="请输入邮箱"
                                      v-model="user.email">
                            </el-input>
                        </el-form-item>
                        <el-form-item :label-width="formLabelWidth" label="手机号码">
                            <el-input autocomplete="off" maxlength="100" placeholder="请输入电话号码"
                                      v-model="user.phone">
                            </el-input>
                        </el-form-item>
                        <el-form-item :label-width="formLabelWidth" label="生日">
                            <div class="block">
                                <el-date-picker
                                        placeholder="选择日期"
                                        type="date"
                                        v-model="value1">
                                </el-date-picker>
                            </div>
                        </el-form-item>
                        <el-form-item :label-width="formLabelWidth" label="地点">
                            <el-input autocomplete="off" maxlength="36" >衡阳市</el-input>
                        </el-form-item>
                    </el-form>
                    <div class="dialog-footer" slot="footer">
                        <el-button @click="updateUser" type="primary" >保存</el-button>
                        <el-button @click="dialogFormVisible = false">取 消</el-button>
                    </div>
                </el-dialog>
                <el-button type="primary">发消息</el-button>
            </div>
        </div>

    </star>
</div>
</body>
<script>
    var v = new Vue({
        el: "#app",
        data: {
            isLiked: false,
            count:10,
            inputVisible: false,
            inputValue: "",
            textarea: "",
            age:'',
            seximg:'',
            user: {
                username: "",
                user_account: "",
                avatarUrl: "",
                gender: "",
                sign:"",
                birthday: "",
                imgs:"",
                phone: "",
                email: "",
                tags: [],
                like:""
            },
            dialogFormVisible: false,
            formLabelWidth: '120px',
            options: [
                { value: 0, label: '男' },
                { value: 1, label: '女' }
            ],
            value1: '',
            tagColors:{}, // 用来存储标签对应的颜色
            file:''
        },
        computed: {
            // 计算图片的 URL
            imageSrc() {
                return this.isLiked ? './asset/已点赞.png' : './asset/点赞.png';
            }
        },
        created() {

            let token = sessionStorage.getItem("Token");
            axios.defaults.headers.common['Token'] = token;
            // 生成每个标签的随机颜色，并存储在 tagColors 对象中
            this.user.tags.forEach(tag => {
                this.$set(this.tagColors, tag, this.getRandomColor());
            });
            axios.get("/user/user/getUser").then(res => {
                if (res.data.code == 1) {
                    this.user = res.data.data;
                    this.user.tags = JSON.parse(this.user.tags);
                    this.value1=this.user.birthday;
                    if (this.user.avatarUrl==null) {
                        this.user.avatarUrl = "./asset/默认图像.png";
                    }
                    const { monthDay, age } = extractMonthDayAndCalculateAge(this.user.birthday);
                    this.user.birthday = monthDay;
                    this.age = age;
                    if (this.user.gender===0){
                        this.seximg="./asset/男女-男.png"
                    }else{
                        this.seximg="./asset/男女-女.png"
                    }
                } else {
                    this.$alert('<strong><a href="login.html">点击跳转登录界面</a></strong>', '您还未登录,请先登录', {
                        dangerouslyUseHTMLString: true
                    });
                }
            }).catch(error=>{
                this.$alert('<strong><a href="login.html">点击跳转登录界面</a></strong>', '您还未登录,请先登录', {
                    dangerouslyUseHTMLString: true
                });
            });
        },
        methods: {
            updateUser(){

                this.user.birthday=this.value1;
                this.user.tags=JSON.stringify(this.user.tags);
                console.log(this.user.tags);
                axios.post("/user/user/updateUser",this.user).then(res => {
                    if (res.data.code == 1) {
                        this.user.tags = JSON.parse(this.user.tags);
                        this.$message({
                            message: '编辑成功',
                            type: 'success'
                        });
                    }else{
                        this.$message.error('更新失败');
                    }
                });
            },
            updateUserTags(){//更改用户标签  增减
                let tags = [];
                this.user.tags.forEach(t=>{
                    tags.push(t);
                })
                axios.post("/user/user/updateUserTags",tags).then(res => {
                    if (res.data.code == 1) {
                        this.$message({
                            message: '编辑成功',
                            type: 'success'
                        });
                    }else{
                        this.$message.error('更新失败');
                    }
                });
            },

            openupload(){
                this.$refs.imgs.click();
            },
            getFile(event) {
                this.file = event.target.files[0];
                let file = new FormData();
                file.append('file', this.file);
                this.uploadImg(file);
            },
            uploadImg(file){
                console.log(file);
                axios.post("star-other/upload/one/image",file, {
                    headers: {
                        'Content-Type': 'multipart/form-data' // 设置请求头为 multipart/form-data
                    }
                }).then(res=>{
                    console.log(res)
                    this.user.avatarUrl=res.data;
                    //添加到数据库
                    this.updateUser();
                })
            },

            getRandomColor() {
                // 生成随机颜色的方法，这里以示例为主，具体可以根据需求实现
                return "#" + Math.floor(Math.random() * 16777215).toString(16);
            },
            handleClose(tag) {
                // 处理标签关闭事件
                const index = this.user.tags.indexOf(tag);
                if (index !== -1) {
                    this.user.tags.splice(index, 1);
                    // 移除对应的颜色
                    this.updateUserTags();
                    this.$delete(this.tagColors, tag);
                }
            },

            showInput() {
                this.inputVisible = true;
                this.$nextTick((_) => {
                    this.$refs.saveTagInput.$refs.input.focus();
                });
            },
            handleInputConfirm() {
                let inputValue = this.inputValue;
                if (inputValue) {
                    this.user.tags.push(inputValue);
                    this.updateUserTags();
                }
                this.inputVisible = false;
                this.inputValue = "";
            },

            toggleLike() {
                this.isLiked = true;
                // 可以在这里增加逻辑来更新点赞数，比如 +1 或 -1
                if (this.count>0){
                    this.user.like += 1;
                    this.count--;
                    axios.get("/user/user/like",  {
                        params: {
                            like: this.user.like,
                            id:this.user.id
                        }}).then(res => {

                    })
                }else{
                    if (this.count==0){
                        this.$message({
                            message: '今日同一好友点赞数已达上限',
                            type: 'warning'
                        });
                    }
                }
            }
        },
    });
</script>
<script>
    function calculateAge(birthdate) {
        const today = new Date();
        const birthDate = new Date(birthdate);
        let age = today.getFullYear() - birthDate.getFullYear();
        const monthDiff = today.getMonth() - birthDate.getMonth();

        if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birthDate.getDate())) {
            age--;
        }

        return age+'岁';
    }


    // 提取月日和计算年龄的方法
    function extractMonthDayAndCalculateAge(dateStr) {
        const dt = new Date(dateStr);

        // 提取月日
        const month = dt.getMonth() + 1; // getMonth() 返回的是0到11
        const day = dt.getDate();
        const monthDay = `${month}月${day}日`;

        // 计算年龄
        const age = calculateAge(dt);

        return { monthDay, age };
    }
</script>
</html>
